package com.gopay.cron.web.util;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.cps.vo.CPSRequest;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.cps.dispatch.CPSCallRemoteService;
import org.apache.log4j.Logger;

/**
 * 访问CPS工具类
 * 
 * @CallCPSUtil.java
 * @author fanghw
 * @2013-2-16 上午11:38:46 www.gopay.com.cn Inc.All rights reserved.
 */
public class CallCPSUtil {

    private static final Logger logger = Logger.getLogger(CallCPSUtil.class);
    /**
     * callCPS服务url
     */
    private static final String URL_CALL_CPS = PropertiesUtil.getValue("cps.remote.url") + "/remote/callCPS";

    /**
     * 根据VO Ticket方式调用CPS
     * 
     * @param v
     * @return
     * @throws MalformedURLException
     */
    public static CPSResponse callByVOTicket(Object v) throws GopayException {
        // v为VO实例
        return callCPS("0", "001", v);
    }
        
    /**
     * stv三个参数方式调用CPS
     * 
     * @param s
     * @param t
     * @param v
     * @return
     * @throws MalformedURLException
     */
    private static CPSResponse callCPS(String s, String t, Object v) throws GopayException {
        CPSResponse response = null;

        try {
            // 封装调用cps服务的请求baggage
            Map<String, Object> baggage = new HashMap<String, Object>();
            baggage.put("s", s);
            baggage.put("t", t);
            baggage.put("v", v);

            // 封装cps请求对象
            CPSRequest request = new CPSRequest();
            request.setSequence(System.currentTimeMillis());
            request.setReqData(baggage);

            // 调用cps服务
            CPSCallRemoteService service = (CPSCallRemoteService)RemoteServiceUtil.getRemoteService(CPSCallRemoteService.class, URL_CALL_CPS);
            response = service.callCPS(request);

            // 校验调用序列值是否相同
            if (response.getSequence() != request.getSequence()) {
                throw new GopayException(ProcCodeConstants.PROC_CODE_100F3001);
            }

        } catch (Exception e) {
            logger.error("调用CPS异常",e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100F3001);
        }
        return response;
    }
}
